package com.springcloud.zuul.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springcloud.zuul.entity.SysMenuEntity;
import com.springcloud.zuul.entity.SysUserEntity;
import com.springcloud.zuul.entity.SysUserTokenEntity;
import com.springcloud.zuul.mapper.SysMenuDao;
import com.springcloud.zuul.mapper.SysUserDao;
import com.springcloud.zuul.mapper.SysUserTokenDao;
import com.springcloud.zuul.service.ShiroService;
import com.springcloud.zuul.service.SysConfigService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public Set<String> getUserPermissions(String userId,String productId) {
        List<String> permsList;

        //手动设置超级管理员,拥有最高权限
        List<String> list = Arrays.asList(sysConfigService.getValue("superAdmin").split(","));
        if(list.contains(userId)){
//            QueryWrapper<SysMenuEntity>queryWrapper=new QueryWrapper<>();
//            queryWrapper.eq("product_id",productId);
//            List<SysMenuEntity> menuList = sysMenuDao.selectList(queryWrapper);
//            permsList = new ArrayList<>(menuList.size());
//            for(SysMenuEntity menu : menuList){
//                permsList.add(menu.getPerms());
//            }
            permsList = sysUserDao.queryAllByProduPerms(productId);
        }else{
            permsList = sysUserDao.queryAllPerms(userId,productId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenDao.queryByToken(token);
    }

    @Override
    public SysUserEntity queryUser(String userId) {
        return sysUserDao.queryByUserId(userId);
    }
}
